from pydantic import BaseModel

# coding: utf-8
from sqlalchemy import BigInteger, CHAR, Column, DateTime, Integer, String, event
from datetime import datetime
from sqlalchemy.sql import func
from models.base import Base
metadata = Base.metadata


class SysPost(Base):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    __tablename__ = 'sys_posts'

    id = Column(BigInteger, primary_key=True, comment='岗位ID')
    post_code = Column(String(64, 'utf8mb4_unicode_ci'), nullable=False, comment='岗位编码')
    post_name = Column(String(50, 'utf8mb4_unicode_ci'), nullable=False, comment='岗位名称')
    post_sort = Column(Integer, nullable=False, comment='显示顺序')
    status = Column(CHAR(1, 'utf8mb4_unicode_ci'), nullable=False, comment='状态（0正常 1停用）')
    create_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='创建者')
    update_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='更新者')
    remark = Column(String(500, 'utf8mb4_unicode_ci'), comment='备注')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    deleted_at = Column(DateTime, comment='删除时间')

@event.listens_for(SysPost, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(SysPost, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")


class SysPostSchema(BaseModel):
    id: int
    post_code: str
    post_name: str
    post_sort: int
    status: str
    create_by: str
    update_by: str
    remark: str
